package freespiritsocial.io.user.ui.fragment.search

import android.os.Bundle
import androidx.lifecycle.ViewModelStoreOwner
import com.scwang.smart.refresh.layout.util.SmartUtil.dp2px
import freespiritsocial.io.user.R
import freespiritsocial.io.user.base.BaseFragment
import freespiritsocial.io.user.data.model.bean.Tag
import freespiritsocial.io.user.databinding.FrgTagsBinding
import freespiritsocial.io.user.decoration.SpaceItemDecoration
import freespiritsocial.io.user.ext.init
import freespiritsocial.io.user.ui.adapter.search.TagsAdapter
import freespiritsocial.io.user.viewmodel.SearchViewModel
import freespiritsocial.io.user.viewmodel.SearchViewModel.Companion.tags
import me.hgj.jetpackmvvm.ext.util.loge

/**
 * @description 搜索标签
 */
class TagsFrg: BaseFragment<SearchViewModel,FrgTagsBinding>() {
    companion object {
        fun crate(viewModelStore: ViewModelStoreOwner) =
            TagsFrg().apply {
                viewModelOwner = viewModelStore
            }

    }

    val adapter by lazy(LazyThreadSafetyMode.NONE) {
        TagsAdapter(mViewModel).apply {
            loadMoreModule.setOnLoadMoreListener {
                data.lastOrNull()?.tagId?.loge("csw")
                mViewModel.getSearchList(tags,data.lastOrNull()?.tagId)
            }
        }
    }

    override fun layoutId(): Int = R.layout.frg_tags

    override fun initView(savedInstanceState: Bundle?) = with(mDatabind) {
        recyclerView.init(adapter,emptyText = getString(R.string.search_empty_message),emptyImage = R.mipmap.empty_search)
            .addItemDecoration(SpaceItemDecoration(0,dp2px(20f)))
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.searchIng.observe(this) {
            if (it) {
                adapter.data.clear()
                mViewModel.getSearchList(tags)
            }
        }
        mViewModel.tagsResult.observe(this) {
            adapter.addData(it)
            adapter.loadMoreModule.loadMoreComplete()
            adapter.loadMoreModule.isEnableLoadMore = it.isNotEmpty()
        }
    }

    fun findTag(tag: Tag) {
        adapter.data.forEachIndexed { index,searchPojo ->
            if (tag.tag == searchPojo.content) {
                mDatabind.recyclerView.scrollToPosition(index)
            }
        }
    }

    inner class Click
}